package com.example.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.domain.entity.Emp;
import com.example.domain.entity.Params;
import com.example.domain.entity.Type;
import com.example.exception.CustomException;
import com.example.mapper.RoomMapper;
import com.example.mapper.TypeMapper;
import com.example.mapper.EmpMapper;
import com.example.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class TypeServiceAImpl implements TypeService {

    @Autowired
    private TypeMapper typeMapper;

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private EmpMapper empMapper;

    @Override
    public List<Type> findAll() {
        return typeMapper.selectList(null);
    }

    @Override
    public Page<Type> findBySearch(Params params) {
        // 查询所有类型
        List<Type> types = typeMapper.selectList(new QueryWrapper<Type>()
                .like(params.getName() != null && !params.getName().isEmpty(), "name", params.getName())
                .orderByDesc("id"));

        // 使用 Stream 流处理数据
        List<Type> result = types.stream().map(type -> {
            // 查询对应的教师信息
            Emp emp = empMapper.selectById(type.getTeacherId());

            // 设置教师名称
            type.setTeacherName(emp != null ? emp.getName() : null);

            return type;
        }).collect(Collectors.toList());

        // 分页处理
        int pageNum = params.getPageNum();
        int pageSize = params.getPageSize();
        int total = result.size();
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);
        List<Type> pageList = result.subList(fromIndex, toIndex);

        // 创建分页对象
        Page<Type> page = new Page<>(pageNum, pageSize, total);
        page.setRecords(pageList);

        return page;
    }

    @Override
    public void add(Type type) {
        if (type.getName() == null || "".equals(type.getName())) {
            throw new CustomException("分类名称不能为空");
        }
        typeMapper.insert(type);
    }

    @Override
    public void update(Type type) {
        if (type.getName() == null || "".equals(type.getName())) {
            throw new CustomException("分类名称不能为空");
        }
        typeMapper.updateById(type);
    }

    @Override
    public void delete(Integer id) {
        int count = roomMapper.selectRoomById(id);
        if(count > 0){
            throw new CustomException("该分类已关联相关自习室，不能删除");
        }
        typeMapper.deleteById(id);
    }

    @Override
    public Type findById(Integer id) {
        return typeMapper.selectById(id);
    }
}